<?php
class M_lessons Extends CI_Model
{
	private $last_insert_id;
	private $lesson_table = 'lessons';
	public function __construct()
	{
		parent::__construct();
		
	}
	
	public function get_all_lessons()
	{
		$query = $this->db->get($this->lesson_table);	
		return $query->num_rows() > 0 ? $query->result() : FALSE;
	}
	
	public function get_all_lessons_per_user($user_id, $sy)
	{	
		$sql = "SELECT * 
				FROM lessons 
				LEFT JOIN lesson_files ON lessons.lesson_file_id = lesson_files.lesson_files_id
				WHERE user_id = ? AND sy_id = ?";
		$query = $this->db->query($sql, array($user_id, $sy));
		return $query->num_rows() > 0 ? $query->result() : FALSE;
	}
	
	public function get_all_level_per_user($user_id)
	{	
		$sql = "SELECT DISTINCT lessons.lvl_id, level_desc 
				FROM levels 
				JOIN lessons ON levels.level_id = lessons.lvl_id
				WHERE user_id = ?";
		$query = $this->db->query($sql, array($user_id));
		return $query->num_rows() > 0 ? $query->result() : FALSE;
	}
	
	public function get_all_section_per_user($user_id)
	{
		$sql = "SELECT DISTINCT lessons.section_id, section_name 
				FROM sections 
				JOIN lessons ON sections.id = lessons.section_id
				WHERE user_id = ?";
		$query = $this->db->query($sql, array($user_id));
		return $query->num_rows() > 0 ? $query->result() : FALSE;
	}
	
	public function add_lesson_file($data)
	{
		$this->db->set($data)->insert('lesson_files',$data);
		return $this->db->affected_rows() ? $this->db->insert_id() : FALSE;
	}
	
	public function add_lesson($data)
	{
		$this->db->set($data)->insert($this->lesson_table,$data);
		$this->last_insert_id = $this->db->insert_id();
		return $this->db->affected_rows() > 0 ? TRUE : FALSE;
		
	}
	
	public function get_lastinsert_id()
	{	
		return $this->last_insert_id;
	}
	
	public function get_this_lesson($id)
	{
		$sql ="SELECT * 
				FROM lessons 
				LEFT JOIN lesson_files ON lessons.lesson_file_id = lesson_files.lesson_files_id
				WHERE lessons.lesson_id = ?";
		$query = $this->db->query($sql,array($id));
		return $query->num_rows() > 0 ? $query->row() : FALSE;
	}
	
	public function update_lesson($data,$id)
	{
		$this->db->set($data)->where('lesson_id',$id)->update($this->lesson_table);
		return $this->db->affected_rows() > 0 ? TRUE : FALSE;
		
	}
	
	
	public function get_specific_coloumn($data,$where = FALSE)
	{	
		if($where == FALSE)
		{
			$query = $this->db->select($data)->get($this->lesson_table );
		}else{
			$query = $this->db->select($data)->where($where)->get($this->lesson_table );
		}
		return $query->num_rows() > 0 ? $query->result() : FALSE;
	}
	
	public function delete_lesson($lesson_id)
	{
		$sql = "DELETE FROM lessons WHERE lesson_id = ?";
		$query = $this->db->query($sql, array($lesson_id));
		return $this->db->affected_rows() > 0 ? TRUE : FALSE;
	}
	
}